﻿using AiMoWindows.Entrance;
using AiMoWindows.Localization;
using AiMoWindows.MainActions;
using AiMoWindows.MainActions.SecondaryActions;
using AiMoWindows.Windows.Login;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;

namespace AiMoWindows.Windows
{
    class UIViewModelBase : ChangeLanguageViewModelBase
    {
        string _TitlePrefix = "AiMo";
        public string TitlePrefix
        {
            get => _TitlePrefix;
            set
            {
                _TitlePrefix = value;
                RaisePropertyChanged(nameof(Title));
            }
        }
        public string Title => TitlePrefix + (Server.ServerHelper.LogInAsCommunityUser ? $" : {Server.ServerHelper.UserName}" : "");
        string titleSuffix = "";
        public string TitleSuffix
        {
            get => titleSuffix;
            set
            {
                titleSuffix = value;
                RaisePropertyChanged(nameof(TitleSuffix));
            }
        }
        readonly Window owner;
        public UIViewModelBase(Window owner) : base()
        {
            this.owner = owner;
            MinimizeCommand = new RelayCommand(() =>
            {
                if (owner.WindowState != WindowState.Minimized)
                {
                    owner.WindowState = WindowState.Minimized;
                }
            });
            MaxmizeCommand = new RelayCommand(() =>
            {
                if (owner.WindowState == WindowState.Maximized)
                {
                    owner.WindowState = WindowState.Normal;
                }
                else owner.WindowState = WindowState.Maximized;
            });
            CloseCommand = new RelayCommand(owner.Close);
            PingCommand = new RelayCommand(() =>
            {
                owner.Topmost = !owner.Topmost;
                SwapImageSource(owner.Topmost);
            });
            InformationCommand = new RelayCommand(InformationButtonClicked);
            CommunityCommand = new RelayCommand(CommunityOrLogin_Click);
            SignOutCommand = new RelayCommand(SignOut);
            _ImageSource = GetImageSource(false);
        }

        #region Command

        public RelayCommand MinimizeCommand { get; }
        public RelayCommand MaxmizeCommand { get; }
        public RelayCommand CloseCommand { get; }
        public RelayCommand PingCommand { get; }
        public RelayCommand InformationCommand { get; }



        #endregion

        #region Login SignOut

        public string CommunityButtonText
            => Server.ServerHelper.LogInAsCommunityUser ?
            (IsEnglish ? "Community" : "AiMo社区") :
            (IsEnglish ? "Login" : "登录");
        public RelayCommand CommunityCommand { get; }
        public RelayCommand SignOutCommand { get; }
        public string SignOutText => IsEnglish ? "Sign Out" : "取消登录";
        void SignOut()
        {
            if (Server.ServerHelper.LogInAsCommunityUser)
            {
                LogOut();
            }
        }
        void LogOut()
        {
            if (MessageBox.Show(owner, Local.Get("Are you sure to logout?"), "", MessageBoxButton.YesNoCancel) != MessageBoxResult.Yes) return;
            {

                Server.ServerHelper.ClearLogin();
                LoginController.ClearRememberPassword();
                AiMoProgram.Instance.UpdateAllWindowState();
            }
        }
        void CommunityOrLogin_Click()
        {
            if (!Server.ServerHelper.LogInAsCommunityUser)
            {
                LoginWindow loginWindow = new LoginWindow();
                if (loginWindow.ShowDialog() ?? false) AiMoProgram.Instance.UpdateAllWindowState();
            }
            else
            {
                ActionsUtils.OpenTutorialWeb();
            }
        }
        #endregion

        #region Font

        public const double MinimumFontSize = 8;
        public const double MaximumFontSize = 72;
        public static bool IsValidFontSize(double value) => value >= MinimumFontSize && value <= MaximumFontSize;

        private double _textFontSize = 12;

        public string FontFamily => IsEnglish ? "Bahnschrift Condensed" : "Microsoft Yahei";
        public double TextFontSize
        {
            get => _textFontSize;
            set
            {
                if (!IsValidFontSize(value))
                {
                    return;
                }

                _textFontSize = value;
                RaisePropertyChanged(nameof(TextFontSize));
            }
        }

        public void MouseWheelChangeSize(object? sender, MouseWheelEventArgs args)
        {
            if (Keyboard.Modifiers == ModifierKeys.Control)
            {
                TextFontSize += args.Delta > 0 ? 1 : -1;
                args.Handled = true;
            }
        }

        #endregion

        #region Information

        protected virtual void InformationButtonClicked()
        {
            if (Server.Attentions.HasAttention)
            {
                var re = MessageBox.Show(owner, Server.Attentions.AttentionContent + Environment.NewLine + Environment.NewLine + Local.Get("Do you want to keep showing this attention?"),
                    Local.Get("!! ATTENTION !!"), MessageBoxButton.YesNoCancel);
                if (re == MessageBoxResult.No)
                {
                    Server.Attentions.CloseCurrentAttention();
                    CurrentInformationState = InformationState.None;
                }
            }
            else if (Server.ServerHelper.HasNewVersion)
            {
                var re = MessageBox.Show(owner, Local.Get("New version is available, click \"OK\" to open down web page")
                    , Local.Get("!! UPDATE !!"), MessageBoxButton.OKCancel);
                if (re == MessageBoxResult.OK)
                {
                    ActionsUtils.OpenTutorialWeb();
                }
            }
        }
        public void UpdateAttention()
        {
            if (Server.Attentions.HasAttention)
            {
                CurrentInformationState = InformationState.Information;
            }
            else if (Server.ServerHelper.HasNewVersion)
            {
                CurrentInformationState = InformationState.NewVersion;
            }
            else CurrentInformationState = InformationState.None;
        }

        InformationState m_CurrentInformationState = InformationState.None;
        public InformationState CurrentInformationState
        {
            get => m_CurrentInformationState;
            set
            {
                m_CurrentInformationState = value;
                RaisePropertyChanged(nameof(InformationVisibility));
            }
        }
        public Visibility InformationVisibility
        {
            get
            {
                switch (m_CurrentInformationState)
                {
                    case InformationState.Information:
                    case InformationState.NewVersion:
                        return Visibility.Visible;
                    default:
                        return Visibility.Collapsed;
                }
            }
        }
        public string InformationText
        {
            get
            {
                switch (CurrentInformationState)
                {
                    case InformationState.Information:
                        return IsEnglish ? "Information" : "通知";
                    case InformationState.NewVersion:
                        return IsEnglish ? "Find New Version" : "发现新版本";
                    default:
                        return "";
                }
            }
        }
        #endregion

        #region Ping
        ImageSource _ImageSource;
        public ImageSource ImageSource
        {
            get => _ImageSource;
            set
            {
                _ImageSource = value;
                RaisePropertyChanged(nameof(ImageSource));
            }
        }
        void SwapImageSource(bool pinged)
        {
            ImageSource = GetImageSource(pinged);
        }
        DrawingImage GetImageSource(bool pinged)
        {
            DrawingImage image = pinged ? (DrawingImage)Application.Current.Resources["PingOn"] : (DrawingImage)Application.Current.Resources["PingOff"];
            return image;
            //return System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(bitmapImage, nint.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
        }
        #endregion
    }
}
